import numpy as np
import pandas as pd
from sklearn.decomposition import PCA

def pca(X,k):#k is the components you want
  #mean of each feature
  n_samples, n_features = X.shape
  mean=np.array([np.mean(X,axis=0)])
  print(mean.shape)
  #normalization
  norm_X=X-mean
  #scatter matrix
  scatter_matrix=np.dot(np.transpose(norm_X),norm_X)
  #Calculate the eigenvectors and eigenvalues
  eig_val, eig_vec = np.linalg.eig(scatter_matrix)
  eig_pairs = [(np.abs(eig_val[i]), eig_vec[:,i]) for i in range(n_features)]
  # sort eig_vec based on eig_val from highest to lowest
  eig_pairs.sort(reverse=True)
  # select the top k eig_vec
  feature=np.array([ele[1] for ele in eig_pairs[:k]])
  #get new data
  data=np.dot(norm_X,np.transpose(feature))
  return data

def pca2(X):
    transfer = PCA(n_components=2)
    data_new = transfer.fit_transform(X)
    print("data_new:\n", data_new)

if __name__ == '__main__':
    sdata = pd.read_excel("硫回收数据.xlsx")
    #pca(sdata,3)
    pca2(sdata)